package com.yakaten.service;

import java.io.BufferedReader;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;


import org.apache.commons.io.IOUtils;

import com.yakaten.dto.RakutenOrderInfoDto;
import com.yakaten.exception.RakutenException;
import com.yakaten.login.RakutenLoginRmsOrder;

public class RakutenOrderService {

	private static final String ORDER_LIST_URL = "https://order.rms.rakuten.co.jp/rms/mall/order/rb/vc?__event=BO01_001_001&status_id=1";

	private static final String REGEX_ORDER_LIST = "<table class=\"orderList\".+?>(.+?)</table><!-- orderList -->";
	private static final Pattern PATTERN_ORDER_LIST = Pattern
			.compile(REGEX_ORDER_LIST);

	private static final String REGEX_NEW_ORDER_COUNT = "全(.*?)件";
	private static final Pattern PATTERN_NEW_ORDER_COUNT = Pattern
			.compile(REGEX_NEW_ORDER_COUNT);

	private static final String REGEX_TR = "<tbody align=\"center\">.*?<tr.+?>.*?"
			+ "<td.*?>(.+?)</td>.*?"
			+ "<td.*?>(.+?)</td>.*?"
			+ "<td class=\"orderNo\">(.+?)</td>.*?"
			+ "<td.*?>(.+?)</td>.*?"
			+ "<td.*?>(.+?)</td>.*?"
			+ "<td.*?>(.+?)</td>.*?"
			+ "<td.*?>(.+?)</td>.*?"
			+ "<td.*?>(.+?)</td>.*?"
			+ "<td.*?>(.+?)</td>.*?"
			+ "<td.*?>(.+?)</td>.*?"
			+ "<td.*?>(.+?)</td>.*?"
			+ "<td.*?>(.+?)</td>.*?"
			+ "<td.*?>(.+?)</td>.*?"
			+ "<td.*?>(.+?)</td>.*?"
			+ "<td.*?>(.+?)</td>.*?"
			+ "<td.*?>(.+?)</td>.*?"
			+ "<td.*?>(.+?)</td>.*?"
			+ "<td.*?>(.+?)</td>.*?"
			+ "<td.*?>(.+?)</td>.*?"
			+ "<td.*?>(.+?)</td>.*?"
			+ "</tr>.*?</tbody>";
	private static final Pattern PATTERN_TR = Pattern.compile(REGEX_TR);

	private static final String REGEX_ORDERNO = "<td class=\"orderNo\">.+?<a.*?>(.*?)</a>.+?</td>";
	private static final Pattern PATTERN_ORDERNO = Pattern
			.compile(REGEX_ORDERNO);

	private static final String REGEX_ORDER_NO = "<a.*?>(.*?)</a>";
	private static final Pattern PATTERN_ORDER_NO = Pattern
			.compile(REGEX_ORDER_NO);

	private static final String REGEX_ORDER_NAME = ".*?<table><tbody>.*?<tr><td>(.*)";
	private static final Pattern PATTERN_ORDER_NAME = Pattern
			.compile(REGEX_ORDER_NAME);

	public Map<String, String> getNewOrderList(String shopId)
			throws RakutenException {

		String url = ORDER_LIST_URL;
		URL targetUrl;
		BufferedReader bufferedReader = null;

		Map<String, String> resultMap = new HashMap<String, String>();
		try {
			targetUrl = new URL(url);
			HttpURLConnection resumeConnection = (HttpURLConnection) targetUrl
					.openConnection();
			resumeConnection.setRequestProperty("Cookie", "shop="
					+ new RakutenLoginRmsOrder().getCookieShop(shopId));

			resumeConnection.connect();
			InputStream urlStream = resumeConnection.getInputStream();
			bufferedReader = new BufferedReader(new InputStreamReader(
					urlStream, "euc-jp"));
			String ss = null;
			StringBuffer total = new StringBuffer();
			while ((ss = bufferedReader.readLine()) != null) {
				total.append(ss);
			}

			Matcher matcherOrderCount = PATTERN_NEW_ORDER_COUNT.matcher(total);

			if (matcherOrderCount.find()) {

				double orderCount = Double.parseDouble(matcherOrderCount
						.group(1));
				int pageCount = (int) Math.ceil(orderCount / 30);

				Matcher matcherOrderList = PATTERN_ORDER_LIST.matcher(total);
				if (matcherOrderList.find()) {
					String orderList = matcherOrderList.group(1);
					// Matcher matcherTr = PATTERN_TR.matcher(orderList);
					Matcher matcherOrderNo = PATTERN_ORDERNO.matcher(orderList);
					while (matcherOrderNo.find()) {
						// orderno
						String orderNo = matcherOrderNo.group(1);
						System.out.println("<tr>");
						getOrderdetailByOrderNumber(shopId, orderNo);
						System.out.println("</tr>");
						Thread.sleep(300);
					}
				}

				if (pageCount > 1) {
					for (int i = 2; i <= pageCount; i++) {
						getNewOrderListByPageId(shopId, i);
					}
				}

			}

			IOUtils.write(total, new FileOutputStream("c:/order.html"),
					"euc-jp");

		} catch (MalformedURLException e) {
			throw new RakutenException(e);
		} catch (IOException e) {
			throw new RakutenException(e);
		} catch (InterruptedException e) {
			e.printStackTrace();
		} finally {
			if (bufferedReader != null) {
				try {
					bufferedReader.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}

		return resultMap;
	}

	private Map<String, String> getNewOrderListByPageId(String shopId,
			int pageId) throws RakutenException {

		String url = "https://order.rms.rakuten.co.jp/rms/mall/order/rb/vc?__event=BO02_001_005&page_number="
				+ pageId;
		URL targetUrl;
		BufferedReader bufferedReader = null;

		Map<String, String> resultMap = new HashMap<String, String>();
		try {
			targetUrl = new URL(url);
			HttpURLConnection resumeConnection = (HttpURLConnection) targetUrl
					.openConnection();
			resumeConnection.setRequestProperty("Cookie", "shop="
					+ new RakutenLoginRmsOrder().getCookieShop(shopId));
			//
			resumeConnection.connect();
			InputStream urlStream = resumeConnection.getInputStream();
			bufferedReader = new BufferedReader(new InputStreamReader(
					urlStream, "euc-jp"));
			String ss = null;
			StringBuffer total = new StringBuffer();
			while ((ss = bufferedReader.readLine()) != null) {
				total.append(ss);
			}

			Matcher matcherOrderList = PATTERN_ORDER_LIST.matcher(total);

			if (matcherOrderList.find()) {

				String orderList = matcherOrderList.group(1);
				// Matcher matcherTr = PATTERN_TR.matcher(orderList);
				Matcher matcherOrderNo = PATTERN_ORDERNO.matcher(orderList);
				while (matcherOrderNo.find()) {
					// orderno
					String orderNo = matcherOrderNo.group(1);
					System.out.println("<tr>");
					getOrderdetailByOrderNumber(shopId, orderNo);
					System.out.println("</tr>");
					Thread.sleep(300);
				}

			}

			IOUtils.write(total, new FileOutputStream("c:/order" + pageId
					+ ".html"), "euc-jp");

		} catch (MalformedURLException e) {
			throw new RakutenException(e);
		} catch (IOException e) {
			throw new RakutenException(e);
		} catch (InterruptedException e) {
			e.printStackTrace();
		} finally {
			if (bufferedReader != null) {
				try {
					bufferedReader.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}

		return resultMap;
	}

	private static final String REGEX_ORDER_DATE = "<tr><th>注文日時</th><td bgcolor=\"#FFFFFF\">(.*?)</td></tr>";
	private static final Pattern PATTERN_ORDER_DATE = Pattern
			.compile(REGEX_ORDER_DATE);

	private static final String REGEX_CUSTOMER_INFO = "<tr><th>注文者情報.*?</th><td bgcolor=\"#FFFFFF\">(.*?)</td></tr>";
	private static final Pattern PATTERN_CUSTOMER_INFO = Pattern
			.compile(REGEX_CUSTOMER_INFO);

	private static final String REGEX_CUSTOMER_ADDRESS = "<tr><th>注文者住所</th><td bgcolor=\"#FFFFFF\">(.*?)</td></tr>";
	private static final Pattern PATTERN_CUSTOMER_ADDRESS = Pattern
			.compile(REGEX_CUSTOMER_ADDRESS);

	private static final String REGEX_CUSTOMER_TEL = "<tr><th>注文者電話番号</th><td bgcolor=\"#FFFFFF\">(.*?)</td></tr><tr>";
	private static final Pattern PATTERN_CUSTOMER_TEL = Pattern
			.compile(REGEX_CUSTOMER_TEL);

	private static final String REGEX_PAY_WAY = "<tr><th>お支払い方法.*?</th><td bgcolor=\"#FFFFFF\">(.*?)</td></tr>";
	private static final Pattern PATTERN_PAY_WAY = Pattern
			.compile(REGEX_PAY_WAY);

	private static final String REGEX_SHIPPING_INFO_TABLE = "<!-- 送付先など --><table class=\"shipInfo\".*?>.*?<tbody>(.*?)</tbody>.*?</table>";
	private static final Pattern PATTERN_SHIPPING_INFO_TABLE = Pattern
			.compile(REGEX_SHIPPING_INFO_TABLE);

	private static final String REGEX_SHIPPING_INFO_TR = "<tr>(.*?)</tr>";
	private static final Pattern PATTERN_SHIPPING_INFO_TR = Pattern
			.compile(REGEX_SHIPPING_INFO_TR);

	private static final String REGEX_SHIPPING_INFO_TD = "<td.*?>(.*?)</td>";
	private static final Pattern PATTERN_SHIPPING_INFO_TD = Pattern
			.compile(REGEX_SHIPPING_INFO_TD);

	private RakutenOrderInfoDto getOrderdetailByOrderNumber(String shopId,
			String orderNumber) throws RakutenException {

		String url = "https://order.rms.rakuten.co.jp/rms/mall/order/rb/vc?__event=BO02_001_013&order_number="
				+ orderNumber;
		URL targetUrl;
		BufferedReader bufferedReader = null;

		RakutenOrderInfoDto orderInfo = new RakutenOrderInfoDto();
		orderInfo.setOrderNumber(orderNumber);

		Map<String, String> resultMap = new HashMap<String, String>();
		try {
			targetUrl = new URL(url);
			HttpURLConnection resumeConnection = (HttpURLConnection) targetUrl
					.openConnection();
			resumeConnection.setRequestProperty("Cookie", "shop="
					+ new RakutenLoginRmsOrder().getCookieShop(shopId));
			//
			resumeConnection.connect();
			InputStream urlStream = resumeConnection.getInputStream();
			bufferedReader = new BufferedReader(new InputStreamReader(
					urlStream, "euc-jp"));
			String ss = null;
			StringBuffer total = new StringBuffer();
			while ((ss = bufferedReader.readLine()) != null) {
				total.append(ss);
			}

			// orderDate
			Matcher matcherOrderDate = PATTERN_ORDER_DATE.matcher(total);
			String orderDate = "";
			if (matcherOrderDate.find()) {
				orderDate = matcherOrderDate.group(1);
				orderInfo.setOrderDate(orderDate);
			}

			// customerInfo
			Matcher matcherCustomerInfo = PATTERN_CUSTOMER_INFO.matcher(total);
			String customerInfo = "";
			String customerName = "";
			if (matcherCustomerInfo.find()) {
				customerInfo = matcherCustomerInfo.group(1);
				String[] tmp = customerInfo.split("<br>");
				customerName = tmp[0];
				orderInfo.setCustomerInfo(customerInfo);
			}

			// customerAdress
			Matcher matcherCustomerAddress = PATTERN_CUSTOMER_ADDRESS
					.matcher(total);
			String customerAddress = "";
			if (matcherCustomerAddress.find()) {
				customerAddress = matcherCustomerAddress.group(1);
				orderInfo.setCustomerAddress(customerAddress);
			}

			// customerTel
			Matcher matcherCustomerTel = PATTERN_CUSTOMER_TEL.matcher(total);
			String customerTel = "";
			if (matcherCustomerTel.find()) {
				customerTel = matcherCustomerTel.group(1);
				orderInfo.setCustomerTel(customerTel);
			}

			// payWay
			Matcher matcherPayWay = PATTERN_PAY_WAY.matcher(total);
			String payWay = "";
			if (matcherPayWay.find()) {
				payWay = matcherPayWay.group(1);
				orderInfo.setPayWay(payWay);
			}

			// shipInfo
			Matcher matcherShippingInfoTable = PATTERN_SHIPPING_INFO_TABLE
					.matcher(total);
			if (matcherShippingInfoTable.find()) {

				String shippingInfoTable = matcherShippingInfoTable.group(1);
				List<List<String>> shippinInfoList = new ArrayList<List<String>>();

				Matcher matcherShippingInfoTr = PATTERN_SHIPPING_INFO_TR
						.matcher(shippingInfoTable);
				while (matcherShippingInfoTr.matches()) {
					List<String> shippinInfoListTr = new ArrayList<String>();
					Matcher matcherShippingInfoTd = PATTERN_SHIPPING_INFO_TD
							.matcher(matcherShippingInfoTr.group(1));
					while (matcherShippingInfoTd.matches()) {
						String td = matcherShippingInfoTd.group(1);
						shippinInfoListTr.add(td);
					}

					shippinInfoList.add(shippinInfoListTr);
				}
				orderInfo.setShippingInfo(shippinInfoList);
			}

		} catch (MalformedURLException e) {
			throw new RakutenException(e);
		} catch (IOException e) {
			throw new RakutenException(e);
		} finally {
			if (bufferedReader != null) {
				try {
					bufferedReader.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}

		return orderInfo;
	}

	public static void main(String args[]) {
		new RakutenLoginRmsOrder().doLogin("298012");

		RakutenOrderService service = new RakutenOrderService();
		Map<String, String> valueMap;
		try {
			// valueMap =
			valueMap = service.getNewOrderList("");
		} catch (RakutenException e) {
			e.printStackTrace();
		}

	}
}
